<template>
  <div class="card">
    <!-- 评论统计 -->
    <div class="flex items-center justify-between mb-6">
      <h3 class="text-xl font-bold text-text-primary">评论 ({{ comments.length }})</h3>
      <div class="flex items-center gap-2">
        <UiButton 
          :variant="sort === 'hot' ? 'secondary' : 'default'"
          size="sm"
          @click="sort = 'hot'"
        >
          热门
        </UiButton>
        <UiButton 
          :variant="sort === 'time' ? 'secondary' : 'default'"
          size="sm"
          @click="sort = 'time'"
        >
          最新
        </UiButton>
      </div>
    </div>

    <!-- 评论输入框 -->
    <div v-if="isAuthenticated" class="mb-6 bg-background-800 rounded-xl p-4">
      <div class="flex gap-3">
        <UiAvatar :src="currentUser?.avatar" :name="currentUser?.name" size="md" />
        <div class="flex-1">
          <textarea 
            v-model="newComment"
            placeholder="分享你的想法..."
            class="input w-full resize-none"
            rows="3"
            :disabled="submitting"
          ></textarea>
          <div class="flex items-center justify-between mt-3">
            <div class="flex items-center gap-4 text-sm text-text-muted">
              <UiCheckbox 
                v-if="isAuthenticated" 
                v-model="isAiComment" 
                :disabled="submitting"
                size="sm"
              >
                AI评论
              </UiCheckbox>
            </div>
            <UiButton 
              variant="primary"
              size="md"
              :disabled="!newComment.trim() || submitting"
              :loading="submitting"
              loading-text="提交中..."
              @click="submitComment"
            >
              发表评论
            </UiButton>
          </div>
        </div>
      </div>
    </div>

    <!-- 未登录提示 -->
    <div v-else class="mb-6 bg-background-800 rounded-xl p-6 text-center">
      <div class="text-text-muted mb-3">
        <svg class="w-12 h-12 mx-auto mb-3 text-text-muted/50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"></path>
        </svg>
        <p class="text-lg font-medium">登录后参与讨论</p>
        <p class="text-sm mt-1">登录后可以发表评论、回复和点赞</p>
      </div>
      <UiButton 
        variant="primary"
        size="md"
        @click="openLoginModal"
      >
        立即登录
      </UiButton>
    </div>

    <!-- 错误提示 -->
    <div v-if="error" class="mb-4 p-3 bg-error/20 text-error rounded-lg border border-error/30">
      {{ error }}
    </div>

    <!-- 加载状态 -->
    <div v-if="loading && comments.length === 0" class="flex justify-center py-8">
      <div class="text-text-muted">加载评论中...</div>
    </div>

    <!-- 评论列表 -->
    <div v-else-if="comments.length > 0" class="space-y-4">
      <CommentCard 
        v-for="comment in displayComments" 
        :key="comment.id" 
        :comment="comment"
        :movieId="movieId"
        @reply="handleReply"
        @like="handleLike"
        @dislike="handleDislike"
        @load-replies="handleLoadReplies"
      />
    </div>

    <!-- 空状态 -->
    <div v-else class="text-center py-8 text-text-muted">
      还没有评论，快来发表第一条评论吧！
    </div>

    <!-- 加载更多 -->
    <div v-if="hasMore && comments.length > 0" class="flex justify-center mt-6">
      <UiButton 
        variant="secondary"
        size="md"
        :loading="loading"
        :disabled="loading"
        @click="loadMore"
      >
        {{ loading ? '加载中...' : '加载更多评论' }}
      </UiButton>
    </div>

    <!-- 没有更多提示 -->
    <div v-else-if="!hasMore && comments.length > 0" class="text-center mt-6 text-text-muted text-sm">
      没有更多评论了
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useCommentLoader, useCommentOperations } from '../../composables/comments'
import { useUserStore } from '../../store/useUserStore'
import { useUiStore } from '../../store/useUiStore'
import { storeToRefs } from 'pinia'
import type { Comment } from '../../types/ui'
import CommentCard from './CommentCard.vue'
import { UiButton, UiCheckbox, UiAvatar } from '../ui'

// Props
interface Props {
  movieId: number
}

const props = defineProps<Props>()

// 使用用户store
const userStore = useUserStore()
const uiStore = useUiStore()
const { isAuthenticated, currentUser } = storeToRefs(userStore)

// 打开登录模态框的方法
const openLoginModal = () => {
  userStore.openLoginModal()
}

// 使用评论composable
const {
  comments,
  loading,
  error,
  hasMore,
  currentPage,
  pageSize,
  loadComments,
  loadMore,
  clearCommentCache,
  clearUserCache,
  getCurrentUser
} = useCommentLoader(props.movieId)

const {
  isSubmitting,
  isLiking,
  submitError,
  likeError,
  submitComment: submitCommentToDb,
  likeComment,
  dislikeComment,
  deleteComment,
  getCommentStats
} = useCommentOperations()

// 本地状态
const sort = ref<'hot'|'time'>('hot')
const newComment = ref('')
const isAiComment = ref(false)
const submitting = ref(false)

// 排序后的评论列表
const sortedComments = computed(() => {
  return [...comments.value].sort((a, b) => b.likes - a.likes)
})

const timeSortedComments = computed(() => {
  return [...comments.value].sort((a, b) => 
    new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime()
  )
})

// 显示的评论列表
const displayComments = computed(() => {
  return sort.value === 'hot' ? sortedComments.value : timeSortedComments.value
})

// 提交评论
const submitComment = async () => {
  if (!isAuthenticated.value) {
    uiStore.showWarning('请先登录后再发表评论')
    return
  }
  
  if (!newComment.value.trim() || submitting.value) return
  
  submitting.value = true
  try {
    const success = await submitCommentToDb(props.movieId, { content: newComment.value })
    if (success) {
      newComment.value = ''
      isAiComment.value = false
      // 重新加载评论列表
      clearCommentCache()
      await loadComments(0, false)
      console.log('评论提交成功')
      uiStore.showSuccess('评论发表成功')
    } else {
      // 显示错误提示
      console.error('提交评论失败:', submitError.value)
      uiStore.showError('评论发表失败: ' + (submitError.value || '未知错误'))
    }
  } catch (error) {
    console.error('提交评论失败:', error)
    uiStore.showError('评论发表失败，请稍后重试')
  } finally {
    submitting.value = false
  }
}

// 处理回复
const handleReply = async (commentId: number, replyContent: string) => {
  if (!isAuthenticated.value) {
    uiStore.showWarning('请先登录后再回复评论')
    return
  }
  
  console.log('开始处理回复:', { commentId, replyContent })
  try {
    const success = await submitCommentToDb(props.movieId, { 
      content: replyContent, 
      parentId: commentId 
    })
    if (success) {
      // 显示成功提示
      console.log('回复成功，已刷新回复列表')
      uiStore.showSuccess('回复成功')
      // 重新加载评论列表
      clearCommentCache()
      await loadComments(0, false)
    } else {
      // 显示错误提示
      console.error('回复失败:', submitError.value)
      uiStore.showError('回复失败: ' + (submitError.value || '未知错误'))
    }
  } catch (error) {
    console.error('回复失败:', error)
    uiStore.showError('回复失败，请稍后重试')
  }
}

// 处理点赞
const handleLike = async (commentId: number) => {
  if (!isAuthenticated.value) {
    uiStore.showWarning('请先登录后再点赞')
    return
  }
  const result = await likeComment(commentId)
  if (result.success) {
    // 实时更新UI状态
    const comment = comments.value.find(c => c.id === commentId)
    if (comment) {
      if (result.action === 'added') {
        // 添加点赞
        comment.likes++
        ;(comment as any).userVote = 1
      } else if (result.action === 'removed') {
        // 取消点赞
        comment.likes--
        ;(comment as any).userVote = 0
      } else if (result.action === 'updated') {
        // 从点踩改为点赞
        comment.dislikes--
        comment.likes++
        ;(comment as any).userVote = 1
      }
    }
  } else {
    uiStore.showError(result.error || '点赞失败')
  }
}

// 处理踩
const handleDislike = async (commentId: number) => {
  if (!isAuthenticated.value) {
    uiStore.showWarning('请先登录后再踩')
    return
  }
  const result = await dislikeComment(commentId)
  if (result.success) {
    // 实时更新UI状态
    const comment = comments.value.find(c => c.id === commentId)
    if (comment) {
      if (result.action === 'added') {
        // 添加点踩
        comment.dislikes++
        ;(comment as any).userVote = -1
      } else if (result.action === 'removed') {
        // 取消点踩
        comment.dislikes--
        ;(comment as any).userVote = 0
      } else if (result.action === 'updated') {
        // 从点赞改为点踩
        comment.likes--
        comment.dislikes++
        ;(comment as any).userVote = -1
      }
    }
  } else {
    uiStore.showError(result.error || '点踩失败')
  }
}

// 处理加载回复
const handleLoadReplies = async (commentId: number) => {
  try {
    // 回复现在在CommentCard组件内部处理，这里不需要额外操作
    console.log('回复加载已在CommentCard组件内部处理')
  } catch (error) {
    console.error('加载回复失败:', error)
  }
}

// 监听排序变化，重新排序评论
watch(sort, () => {
  // 排序是计算属性，会自动更新
})

// 组件挂载时加载数据
onMounted(async () => {
  // 加载评论
  await loadComments()
})
</script>